import requests
import pickle
import os
from config.config import COOKIE_FILE, LOGIN_URL, LOGIN_DATA, HEADERS


def login():
    session = requests.Session()
    response = session.post(LOGIN_URL, json=LOGIN_DATA, headers=HEADERS)
    if response.status_code == 200:
        with open(COOKIE_FILE, 'wb') as f:
            pickle.dump(session.cookies, f)
        print("登录成功")
        return session
    else:
        raise Exception(f"登录失败：{response.status_code} - {response.text}")


def get_session():
    session = requests.Session()
    if os.path.exists(COOKIE_FILE):
        try:
            with open(COOKIE_FILE, 'rb') as f:
                session.cookies.update(pickle.load(f))
            # 验证 cookies 是否有效（用一个简单 GET 请求测试）
            test_url = "https://wl.gkzycc.cn/data/collegeList"
            if session.get(test_url).status_code == 200:
                print("使用已保存的 cookies")
                return session
        except Exception as e:
            print(f"cookies 无效: {e}")

    print("重新登录获取 cookies")
    return login()
